package io.dshubs.archives.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.dshubs.archives.dao.ArchiveBaseInfoMapper;
import io.dshubs.archives.dao.ArchiveBaseRuleMapper;
import io.dshubs.archives.entity.ArchiveBaseInfo;
import io.dshubs.archives.entity.ArchiveBaseRule;
import io.dshubs.archives.service.ArchiveBaseInfoService;
import io.dshubs.commons.log.annotation.LogOperation;
import io.dshubs.commons.mybatis.annotation.DataFilter;
import io.dshubs.commons.tools.constant.Constant;
import io.dshubs.commons.tools.page.PageData;
import io.dshubs.commons.tools.utils.Result;
import io.dshubs.commons.tools.validator.ValidatorUtils;
import io.dshubs.commons.tools.validator.group.AddGroup;
import io.dshubs.commons.tools.validator.group.DefaultGroup;
import io.dshubs.commons.tools.validator.group.UpdateGroup;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 全宗信息表 前端控制器
 * </p>
 *
 * @author tan
 * @since 2021-08-16
 */
@RestController
@RequestMapping("info")
@Api(tags="全宗管理")
public class ArchiveBaseInfoController {

    @Autowired
    private ArchiveBaseInfoService archiveBaseInfoService;

    @Autowired
    private ArchiveBaseRuleMapper archiveBaseRuleMapper;

    @Autowired
    private ArchiveBaseInfoMapper archiveBaseInfoMapper;

    @GetMapping("page")
    @ApiOperation("全宗管理:page")
    @LogOperation("全宗管理:page")
    @ApiImplicitParams({
            @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType="int") ,
            @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query",required = true, dataType="int") ,
            @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType="String") ,
            @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType="String") ,
            @ApiImplicitParam(name = "code", value = "全宗号", paramType = "query", dataType="String"),
            @ApiImplicitParam(name = "tenantCode", value = "组织机构", paramType = "query", dataType="String")
    })
    @PreAuthorize("hasAuthority('archive:info:page')")
    public Result<PageData<ArchiveBaseInfo>> page(@ApiIgnore @RequestParam Map<String, Object> params){
        return new Result<PageData<ArchiveBaseInfo>>().ok(archiveBaseInfoService.page(params));
    }

    @GetMapping("/list")
    @ApiOperation("详情")
    @LogOperation("全宗管理:list")
    @PreAuthorize("hasAuthority('archive:info:list')")
    public Result<List<ArchiveBaseInfo>> list(@ApiIgnore @RequestParam Map<String, Object> params){
        return new Result<List<ArchiveBaseInfo>>().ok(archiveBaseInfoService.list(params));
    }

    @GetMapping("{id}")
    @ApiOperation("详情")
    @LogOperation("全宗管理:get")
    public Result<ArchiveBaseInfo> get(@PathVariable("id") Long id){
        ArchiveBaseInfo archiveBaseInfo = archiveBaseInfoService.selectById(id);
        List<ArchiveBaseRule> baseRuleList = archiveBaseRuleMapper.selectList(new QueryWrapper<ArchiveBaseRule>().eq("archive_id", archiveBaseInfo.getId()));
        if(CollectionUtils.isNotEmpty(baseRuleList)) {
            archiveBaseInfo.setRuleArchiveId(baseRuleList.stream().map(j->{
                if("FIELD_JOINT".equals(j.getLabel())) {
                    j.setLabel(j.getValue());
                }
                return j.getLabel();
            }).collect(Collectors.joining("")));
        }

        return new Result<ArchiveBaseInfo>().ok(archiveBaseInfo);
    }

    @PostMapping
    @ApiOperation("保存")
    @LogOperation("全宗管理:save")
    @PreAuthorize("hasAuthority('archive:info:save')")
    public Result save(@RequestBody ArchiveBaseInfo archiveBaseInfo){
        //效验数据
        ValidatorUtils.validateEntity(archiveBaseInfo, AddGroup.class, DefaultGroup.class);

        archiveBaseInfoService.save(archiveBaseInfo);
        return new Result();
    }

    @PutMapping
    @ApiOperation("修改")
    @LogOperation("全宗管理:update")
    @PreAuthorize("hasAuthority('archive:info:update')")
    public Result update(@RequestBody ArchiveBaseInfo archiveBaseInfo){
        //效验数据
        ValidatorUtils.validateEntity(archiveBaseInfo, UpdateGroup.class, DefaultGroup.class);
        archiveBaseInfoService.deleteById(archiveBaseInfo);
        archiveBaseRuleMapper.delete(
                new QueryWrapper<ArchiveBaseRule>().eq("archive_id",archiveBaseInfo.getId()));
        archiveBaseInfo.setId(null);
        archiveBaseInfoService.save(archiveBaseInfo);

        return new Result();
    }

    @DeleteMapping()
    @ApiOperation("删除")
    @LogOperation("全宗管理:delete")
    @PreAuthorize("hasAuthority('archive:info:delete')")
    public Result delete(@RequestBody @NotNull(message = "批量删除id不能为空") List<Long> ids){
        archiveBaseInfoService.deleteBatchIds(ids);
        archiveBaseRuleMapper.delete(new QueryWrapper<ArchiveBaseRule>().in("archive_id",ids));
        return new Result();
    }

    @DeleteMapping("/code")
    @ApiOperation("删除")
    @LogOperation("全宗管理:deleteByCode")
    @PreAuthorize("hasAuthority('archive:info:delete')")
    public Result deleteByCode(@RequestBody @NotNull(message = "批量删除id不能为空") List<Long> code){
        List<ArchiveBaseInfo> archiveBaseInfos = archiveBaseInfoMapper.selectList(new QueryWrapper<ArchiveBaseInfo>().in("tenant_code", code));
        if(CollectionUtils.isNotEmpty(archiveBaseInfos)) {
            List<Long> idList = archiveBaseInfos.stream().map(ArchiveBaseInfo::getId).collect(Collectors.toList());
            delete(idList);
        }
        return new Result();
    }
}
